# 导入相关库和模块
from contextlib import contextmanager
from typing import Union, Dict, List, Any
from database import SessionLocal
from models.permission import Permission
from typing import List
from config.logging import logger
from services.database_manager import databaseManager
from models.role import Role, RoleSchema
from models.admin_user import AdminUser
# 定义服务类
class UserRoleApiService:
    def __init__(self, db):
        self.db = db
        self.db_manager = databaseManager(self.db)

    async def list_user_roles(self, page, limit, name=None) -> Dict[str, Union[List[Any], Any]] :
        """
        角色列表
        :param page:
        :param limit:
        :param name:
        :return:
        """
        query = self.db.query(Role)
        if name:
            query = query.filter(Role.name == name)
        lists = self.db_manager.paginate_query(query, page, limit)
        roles = [RoleSchema.from_orm(role) for role in lists] if lists else []
        # 转换为字典并进行键名转换
        roles_dict = [self.db_manager.convert_dict_keys(role.dict()) for role in roles]

        return {"list": roles_dict, "total": query.count()}

    async def detail_user_role(self, role_id=None, user_id=None):
        """
        获取角色详情或用户所属角色列表
        :param role_id: 角色ID
        :param user_id: 用户ID
        :return: 角色详情或用户所属角色列表
        """
        # 如果提供了user_id，则查询用户的角色列表
        if user_id is not None:
            user_role = self.db.query(AdminUser).get(user_id)  # 修正了变量名错误
            if user_role:
                roles_of_admin = user_role.roles
                return roles_of_admin
            else:
                # 用户未找到时，可以返回空列表或抛出异常，视业务需求而定
                return []  # 或者 raise 异常类型("用户未找到")

        # 如果提供了role_id，则查询角色详情
        if role_id is not None:
            info = self.db_manager.detail_query(Role, {"id": role_id})
            res = RoleSchema.from_orm(info)
            return self.db_manager.convert_dict_keys(res.dict())

        return None  # 或者 raise 异常类型("必须提供role_id或user_id")

    async def create_user_role(self, data):
        """
        创建新角色
        :param data:
        :return:
        """
        if self.db_manager.detail_query(Role, {"name": data["name"]}):
            return {"error": "角色已存在"}
        self.db_manager.create_entry(Role, {"name": data["name"], "description": data["desc"]})
        return True

    async def update_user_role(self, data, role_id):
        """
        更新角色
        :param role_id:
        :param data:
        :return:
        """
        if self.db_manager.detail_query(Role, {"id": role_id}) is None:
            return {"error": "角色不存在"}
        self.db_manager.detail_update(Role, {"id": role_id}, {"name": data["name"], "description": data["desc"]})
        return True

    async def delete_user_role(self, ids):
        """
        删除
        :param ids:
        :return:
        """
        self.db_manager.delete_records_by_ids(Role, ids)
        return True

    async def assign_permissions_to_role(self, permissionData):
        """
        授权权限给角色
        """
        permissionData = self.db_manager.snake_convert_dict_keys(permissionData)
        role = self.db_manager.detail_query(Role, {"id": permissionData["role_id"]}, needRow=True)
        if role is None:
            return {"error": "角色不存在"}
        permissions_ids = permissionData["permission_ids"].split(',')  # 拆分为单独的id
        for permission_id in permissions_ids:
            permission_id = int(permission_id.strip())
            permission = self.db_manager.detail_query(Permission, {"id": permission_id}, needRow=True)
            if permission is None:
                return {"error": "权限不存在"}
            role.permissions.append(permission)
            logger.info(f"已将权限 {permission.id} 添加到角色 {role.id}")
        self.db_manager.commit()
        return True

    async def assign_user_to_roles(self, data):
        user = self.db_manager.detail_query(AdminUser, {"id": data["userId"]}, needRow=True)
        if user is None:
            return {"error": "用户不存在"}
        role = self.db_manager.detail_query(Role, {"id": data["roleId"]}, needRow=True)
        if role is None:
            return {"error": "角色不存在"}

        user.roles.append(role)
        self.db_manager.commit()
        return True




